﻿using Microsoft.AspNetCore.Mvc;
using Ls.Utils;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Ls.Web.Framework.Permissions;
using System.Security.Claims;
using Microsoft.AspNetCore.Hosting;
using Ls.Data;

namespace Ls.Web.Framework
{
    public class BaseController: Controller
    {

        #region  excel
        public IActionResult Xlsx()
        {
            return null;
        }
        public IActionResult Xlsx(byte[] data, string fileName)
        {
            return File(data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        }
        public IActionResult Xlsx(List<dynamic> dataList,  string title)
        {
            return Xlsx(dataList, CommonHelper.GetColumns(), title);
        }
       
        public IActionResult Xlsx(List<dynamic> dataList, Dictionary<string, string> columns, string title)
        {
            return Xlsx(NPOIHelper.ExportXLSX(dataList, columns, title), title + ".xlsx");
        }

        public IActionResult Xlsx(List<dynamic> dataList, List<ExcelColumn> columns, string title)
        {
            return Xlsx(NPOIHelper.ExportXLSX(dataList, columns, title), title + ".xlsx");
        }
        #endregion


        #region 获取成功结果 GetSuccessResult
        /// <summary>
        /// 获取成功结果
        /// </summary>
        /// <returns></returns>
        public JsonResult GetSuccessResult()
        {
            return GetSuccessResult("操作成功！");
        }
        /// <summary>
        /// 获取成功结果
        /// </summary>
        /// <param name="code"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public JsonResult GetSuccessResult(string message)
        {
            return Json(new { statusCode = ResultCode.Success, info = message });
        }

        /// <summary>
        /// 获取返回结果
        /// </summary>
        /// <param name="code"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public JsonResult GetResultData(string code, object data)
        {
            return Json(new { statusCode = code, data = data });
        }

        /// <summary>
        /// 获取成功结果
        /// </summary>
        /// <param name="code"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public JsonResult GetSuccessResult(object data)
        {
            return Json(new { statusCode = ResultCode.Success, data = data });
        }
        /// <summary>
        /// 获取返回结果
        /// </summary>
        /// <param name="code"></param>
        /// <param name="message"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public JsonResult GetSuccessResult(string message, object data)
        {
            return Json(new { statusCode = ResultCode.Success, info = message, data = data });
        }
        #endregion

        #region 获取失败结果 GetErrorResult
        /// <summary>
        /// 获取失败结果
        /// </summary>
        /// <param name="code"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public JsonResult GetErrorResult()
        {
            return Json(new { statusCode = ResultCode.Error, info = "操作失败！" });
        }
        /// <summary>
        /// 获取失败结果
        /// </summary>
        /// <param name="code"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public JsonResult GetErrorResult(string message)
        {
            return Json(new { statusCode = ResultCode.Error, info = message });
        }

        /// <summary>
        /// 获取失败结果
        /// </summary>
        /// <param name="code"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public JsonResult GetErrorResultFormat(string messageformat, params object[] parameters)
        {
            return Json(new { statusCode = ResultCode.Error, info = string.Format(messageformat, parameters) });
        }
        /// <summary>
        /// 获取失败结果
        /// </summary>
        /// <param name="code"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public JsonResult GetErrorResult(Exception ex)
        {
            return Json(new { statusCode = ResultCode.Error, info = "操作失败！异常内容：" + ex.Message });
        }
        #endregion

        #region 获取返回结果
        /// <summary>
        /// 获取返回结果
        /// </summary>
        /// <param name="code"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public JsonResult GetResultMsg(string code, string message)
        {
            return Json(new { statusCode = code, info = message });
        }

        /// <summary>
        /// 获取返回结果
        /// </summary>
        /// <param name="code"></param>
        /// <param name="message"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public JsonResult GetResultObj(string code, string message, object data)
        {
            return Json(new { statusCode = code, info = message, data = data });
        }
        #endregion
 
        #region 受保护的方法
        /// <summary>
        /// 检查当前用户是否有某个权限
        /// </summary>
        /// <param name="permissionName"></param>
        /// <returns></returns>
        protected bool CheckPermission(string permissionName)
        {
            var service = HttpContext.RequestServices.GetRequiredService<IPermissionService>();
            string userId = HttpContext.User.FindFirstValue("userid");// 用户id
            var sup = HttpContext.User.FindFirstValue("is_sup"); // 是否是超级管理员
            if (sup == "1") return true;
            return service.CheckPermission(CommonHelper.ToInt64(userId), permissionName);
        }

        protected IHostingEnvironment Environment
        {

            get
            { 
                var env = HttpContext.RequestServices.GetRequiredService<IHostingEnvironment>(); 
                return env;
            }
        }
        #endregion
        #region db
        private IDbContext _db = null;
        public IDbContext db
        {
            get
            {
                if (_db == null)
                {
                    _db = new DbContext().ConnectionStringName("Default", new MySqlProvider());
                }
                return _db;
            }
        }
        #endregion
        #region 用户信息

        /// <summary>
        /// 用户Id
        /// </summary>
        public long UserId
        {
            get
            {

                string userId = HttpContext.User.FindFirstValue("userid");
                if (userId.IsNullOrEmpty())
                {
                    return 0;
                }
                else
                {
                    return CommonHelper.ToInt64(userId);
                }
            }
        }
        /// <summary>
        /// 真实姓名
        /// </summary>
        public string UserRealName {

            get {
                if (UserInfo != null)
                {
                    return UserInfo.realName;
                }
                return ""; 
            }
        }

        public void RemoveUserInfoCache(long user_id) {
            CacheHelper.Remove("APPUSER:" + user_id);
        } 
        /// <summary>
        /// 当前用户信息
        /// </summary>
        public UserInfo UserInfo
        { 
            get
            {
                if (UserId ==0)
                {
                    return null;
                }  
                long org_id = 0;
                var userInfo = new UserInfo();
                userInfo.userId = UserId;
                string userInfoKey = "APPUSER:" + userInfo.userId.ToString();
                var newUserInfo = CacheHelper.Get<UserInfo>(userInfoKey);

                if (newUserInfo != null)
                {
                    return newUserInfo;
                }
                else
                {
                    string sql = @"select user_id,nickname,realname,username,userpwd,salt,is_sup,user_type,org_id 
                                from sys_users
                                where user_id=@user_id and user_status = 0 and user_type = 2";
                    dynamic user = db.Sql(sql).Parameter("user_id", UserId).QuerySingle<dynamic>();

                    if (user == null)
                    {
                        return null;
                    }
                    else
                    {
                        userInfo.userId = CommonHelper.ToInt64(user.user_id);
                        org_id = CommonHelper.ToInt64(user.org_id);
                        userInfo.orgId = org_id;
                        userInfo.realName = CommonHelper.ToString(user.realname);
                    }
                  
                    string sqlStore = @"select a.org_id as store_id,a.org_code as store_code,a.org_name as store_name,
                                      b.org_id as carrier_id,b.org_code as carrier_code,b.org_name as carrier_name 
                from sys_org a left join  sys_org b on a.parent_id = b.org_id 
                where a.org_id = @org_id";
                    dynamic storeInfo =  db.Sql(sqlStore).Parameter("org_id", org_id).QuerySingle<dynamic>();
                    if (storeInfo != null)
                    {
                        userInfo.storeId = CommonHelper.ToInt64(storeInfo.store_id);
                        userInfo.storeCode = CommonHelper.ToString(storeInfo.store_code);
                        userInfo.storeName = CommonHelper.ToString(storeInfo.store_name);
                        userInfo.carrierId = CommonHelper.ToInt64(storeInfo.carrier_id);
                        userInfo.storeCode = CommonHelper.ToString(storeInfo.store_code);
                        userInfo.carrierCode = CommonHelper.ToString(storeInfo.carrier_code);
                        userInfo.carrierName = CommonHelper.ToString(storeInfo.carrier_name);
                    }
                    string sqlWh = @"select wh_id,wh_name from wh_warehouse where from_type = 0 and wh_state =0 and is_del =0 and from_id = " + org_id;
                    List<dynamic> whList = db.Sql(sqlWh).QueryMany<dynamic>();
                    if (whList != null && whList.Count > 0)
                    {
                        userInfo.whId = whList[0].wh_id;
                        userInfo.whName = whList[0].wh_name;
                    }

                    CacheHelper.Set(userInfoKey, userInfo);
                   
                    return userInfo;
                } 
            }
        }

        /// <summary>
        /// 仓库Id
        /// </summary>
        public long WhId {

            get {
                if (UserInfo != null)
                {
                    return UserInfo.whId;
                }
                return 0;
            }
        }
        #endregion

        //public IActionResult Jsonp(object data) {
        //    return 
        //}
    }
}
